<template>
  <el-form ref="dataForm" :rules="rules">
    <el-form-item style="text-align: center">
      <el-upload
        class="avatar-uploader"
        :action="uploadUrl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="user.avatar" :src="user.avatar" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon" />
      </el-upload>
    </el-form-item>
    <el-form-item label="用户名" prop="username">
      <el-input v-model.trim="user.name" disabled />
    </el-form-item>
    <el-form-item label="用户名" prop="nickname">
      <el-input v-model.trim="user.nickname" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model.trim="user.email" />
    </el-form-item>
    <el-form-item label="手机号码" prop="mobile">
      <el-input v-model.trim="user.mobile" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model.trim="user.password" type="password" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">更新</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { modify as update } from '@/api/user'
export default {
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          name: '',
          email: '',
          nickname: '',
          password: '',
          mobile: '',
          avatar: ''
        }
      }
    }
  },
  data() {
    return {
      password: '',
      uploadUrl: process.env.VUE_APP_BASE_API + '/index/index/upload',
      imageUrl: '',
      rules: {
        nickname: [{ required: true, message: '昵称必填', trigger: 'change' }],
        mobile: [{ required: true, message: '手机号必填', trigger: 'change' }],
        email: [{ required: true, message: '邮箱必填', trigger: 'change' }]
      }
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.user.avatar = res.data.url
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    submit() {
      update(this.user).then(() => {
        this.$notify({
          title: 'Success',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
</style>
